import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/wallhaven.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class NekosiaPage extends StatefulWidget {
  const NekosiaPage({super.key});

  @override
  State<NekosiaPage> createState() => _NekosiaPageState();
}

class _NekosiaPageState extends State<NekosiaPage> {
  // 常规
  List types = [
    ["animal-ears", "兽耳"],
    ["cute", "可爱"],
    ["cat-ears", "猫耳"],
    ["catgirl", "猫娘"],
    ["tail", "尾巴"],
    ["young-girl", "少女"],
    ["blue-eyes", "蓝眼"],
    ["uniform", "制服"],
    ["white-hair", "白发"],
    ["thigh-high-socks", "过膝袜"],
    ["skirt", "裙子"],
    ["ribbon", "缎带"],
    ["vtuber", "虚拟主播"],
    ["thighs", "大腿"],
    ["girl", "女孩"],
    ["tail-with-ribbon", "带缎带的尾巴"],
    ["fox-ears", "狐耳"],
    ["foxgirl", "狐娘"],
    ["pink-hair", "粉发"],
    ["sailor-uniform", "水手服"],
    ["white-thigh-high-socks", "白色过膝袜"],
    ["smile", "微笑"],
    ["wolf-girl", "狼女"],
    ["tail-from-under-skirt", "裙底的尾巴"],
    ["cuteness-is-justice", "可爱就是正义"],
    ["blue-archive", "碧蓝档案"],
    ["maid", "女仆"],
    ["maid-uniform", "女仆制服"],
    ["w-sitting", "w-sitting"],
    ["lying-down", "躺着"],
    ["hands-forming-a-heart", "手形成心形"],
    ["wink", "眨眼"],
    ["valentine", "情人节"],
    ["headphones", "耳机"],
    ["knee-high-socks", "及膝袜"],
    ["white-tights", "白色紧身裤"],
    ["black-tights", "黑色紧身裤"],
    ["heterochromia", "异色症"],
    ["hoodie", "连帽衫"],
    ["blue-hair", "蓝发"],
    ["long-hair", "长发"],
    ["blonde", "金发女郎"],
    ["purple-eyes", "紫眼睛"],
    ["pink", "粉色"],
  ];

  final List<dynamic> imgs = [];
  final Set<String> results = <String>{};
  bool isLoading = false;
  List<String> tags = ['cute', 'young-girl'];

  Future<void> getImageData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await nekosiaSearch(
        tags: tags,
      );
      List images = res.data['images'];

      for (var i = 0; i < images.length; i++) {
        ImageBase image = ImageBase(
          largePath: images[i]['image']['original']['url'],
          smallPath: images[i]['image']['compressed']['url'],
          tags: '',
          width: images[i]['metadata']['compressed']['width'] ?? 1,
          height: images[i]['metadata']['compressed']['height'] ?? 1.7,
        );
        if (!results.contains(image.smallPath)) {
          results.add(image.smallPath);
          imgs.add(image);
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getImageData();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        backgroundColor: theme.primaryContainer,
        surfaceTintColor: theme.primaryContainer,
        elevation: 0,
      ),
      endDrawer: Drawer(
        // 设置圆角
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.zero),
        ),
        backgroundColor: Colors.black.withOpacity(0.5),
        child: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.only(top: 50, bottom: 20, left: 15, right: 15),
          child: Column(
            children: [
              Expanded(
                child: ListView(
                  children: [
                    Wrap(
                      spacing: 10,
                      runSpacing: 10,
                      alignment: WrapAlignment.start,
                      children: [
                        for (var i = 0; i < types.length; i++)
                          buildImageTypes(i, theme, types),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 35,
                child: NormalButton(
                  title: '搜素',
                  radius: 3,
                  bgColor: Colors.white.withOpacity(0.2),
                  onPressed: () {
                    if (tags.isEmpty) {
                      BotToast.showText(text: '至少选择一个标签');
                      return;
                    }
                    setState(() {
                      imgs.clear();
                      results.clear();
                    });
                    getImageData();
                    Navigator.of(context).pop();
                  },
                ),
              )
            ],
          ),
        ),
      ),
      body: ImageList(
          imageList: imgs,
          isLoading: isLoading,
          isWaterfallFlow: true,
          onImageBottomLoading: () {
            if (!isLoading) {
              getImageData();
            }
          },
          onImageListRefresh: () {
            setState(() {
              imgs.clear();
              results.clear();
            });
            getImageData();
          }),
    );
  }

  Widget buildImageTypes(int i, ColorScheme theme, List types) {
    return Material(
      // 圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(3),
      ),
      color: tags.contains(types[i][0])
          ? theme.primary
          : Colors.white.withOpacity(0.2),
      clipBehavior: Clip.antiAlias,
      child: InkWell(
        onTap: () {
          if (tags.contains(types[i][0])) {
            setState(() {
              tags.remove(types[i][0]);
            });
          } else {
            setState(() {
              tags.add(types[i][0]);
            });
          }
        },
        child: Padding(
          padding: const EdgeInsets.only(
            left: 10,
            right: 10,
            top: 5,
            bottom: 5,
          ),
          child: Text(
            types[i][1],
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}
